package com.zysstudy.collection;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @author zhaoyoushui
 * @date 2025/4/19 15:57
 * @Description
 * @Copyright 南京优通信息科技股份有限公司
 */
public class MapStudy {

    /**
     * 1.绝大多数情况： HashMap 是首选，又快又好用。
     * <p>
     * 2.需要记住插入顺序或访问顺序： LinkedHashMap。
     * <p>
     * 3.需要对 Key 进行排序： TreeMap。
     * <p>
     * 3.多线程并发环境： ConcurrentHashMap。
     */
    public static void main(String[] args) {
        MapStudy t = new MapStudy();
        t.p1();
        t.p2();
    }

    public void p1() {
        Map<String, Object> map1 = new HashMap<>();
        map1.put("k1", 1);
        map1.put("k2", "12345");
        map1.put("k3", 1.234);
        //判断键是否存在  感觉类似php isset()
        if (map1.containsKey("k3")) {
            System.out.println("存在Key为:k3，其值为" + map1.get("k3"));
        }

        for (String key : map1.keySet()) {
            System.out.println("keySet 所有key" + key);
        }
        for (Object val : map1.values()) {
            System.out.println("获得values获得所有value" + val);
        }
        for (Map.Entry<String, Object> val : map1.entrySet()) {
            System.out.println("entrySet取出键值对,key:" + val.getKey() + "--value:" + val.getValue());
        }

        String text = "apple banana orange apple banana";
        String[] words = text.split(" ");
        Map<String, Integer> wordCount = new HashMap<>();
        for (String item : words) {
            Integer count = wordCount.getOrDefault(item, 0) + 1;
            wordCount.put(item, count);
        }
        System.out.println("getOrDefault 使用,统计打印" + wordCount);
    }

    // tomap entrySet
    public void p2() {
        String input = "Hello, World! 123";
        System.out.println("字符串是：" + input);
        Map<Character, Integer> countMap = new HashMap<>();
        for (char ch : input.toCharArray()) {
            if (Character.isLetter(ch)) {
                int num = countMap.getOrDefault(ch, 0) + 1;
                countMap.put(ch, num);
            }
        }
        System.out.println("打印出统计字母map" + countMap);
        Map<Character, Integer> res = countMap.entrySet().stream()
                .sorted((a, b) -> b.getKey().compareTo(a.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(o,n)->o, LinkedHashMap::new));
        System.out.println("按字母排序" + res);

        Map<Character,Integer> res2 = countMap.entrySet()
                .stream()
                .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(o,n)->n, TreeMap::new));
        System.out.println("按字母排序" + res2);

        Map<Character, Integer> res3 = countMap.entrySet().stream()
                .sorted((a, b) -> b.getValue().compareTo(a.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(o,n)->o, LinkedHashMap::new));
        System.out.println("按值排序" + res3);
    }


}
